#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


// version 1
class Solution {
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
        int n = mat.size(), m = mat[0].size();
        vector<vector<int>> answer(n, vector<int>(m, 0));

        //使用long long防止溢出 
        vector<vector<long long>> dp(n + 1, vector<long long>(m + 1, 0));
        for(int i = 1; i <= n; ++i){
            for(int j = 1; j <= m; ++j){
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }


        for(int i = 0; i < n; ++i){
            for(int j = 0; j < m; ++j){
                //计算一下当前需要化范围的矩阵，防止越界
                int x1 = max(i - k, 0), y1 = max(j - k, 0);
                int x2 = min(i + k, n - 1), y2 = min(j + k, m - 1);

                //获得了一个由(x1,x2) (y1, y2)左上角和右下角构成的矩阵
                //这个矩阵的和就是当前answer[i][j]的答案
                answer[i][j] = dp[x2 + 1][y2 + 1];
                if(y1 - 1 >= 0 && x1 - 1 >= 0) 
                    answer[i][j] = answer[i][j] - dp[x2 + 1][y1] - dp[x1][y2 + 1] + dp[x1][y1];
                else if(y1 - 1 >= 0) answer[i][j] = answer[i][j] - dp[x2 + 1][y1];
                else if(x1 - 1 >= 0) answer[i][j] = answer[i][j] - dp[x1][y2 + 1];
            }
        }
        return answer;

    }
};